(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
      (global.huiTags = factory());
}(this, (function () {
  layui.define(["jquery", "laypage", 'dtree', 'table', 'upload'], function (exports) {
    var $ = layui.$;
    var laypage = layui.laypage;
    var table = layui.table;
    var dtree = layui.dtree;
    var upload = layui.upload;
    var inputSelectId = '';
    var inputType = 'more';
    var group_id = -1;
    var page = 1;
    STORE_URL = GV.admin_module_name;

    var chunkSize = typeof GV.site.chunksize !== "undefined" ? GV.site.chunksize : 204800;
    var Exts = GV.site.upload_image_ext;
    var uploadUrl = GV.upload_url;
    Exts = Exts.replace(/,/g, "|");

    var DTree = dtree.render({
      elem: "#organizationTree",
      //data: data,
      initLevel: "2", //默认展开层级为1
      line: true, // 有线树
      ficon: ["1", "-1"], // 设定一级图标样式。0表示方形加减图标，8表示小圆点图标
      icon: ["0", "5"], // 设定二级图标样式。0表示文件夹图标，5表示叶子图标
      method: 'get',
      width: '93%',
      url: STORE_URL + 'system/uplibrary/group_list',
      toolbar: true,
      toolbarStyle: {
        title: "分组名称",
        area: ["55%", "400px"]
      },
      toolbarWay: "fixed",
      toolbarShow: ["add", "edit", "delete"],
      toolbarFun: {
        loadToolbarBefore: function (buttons, param, $div) {
          // 如果是叶子节点
          if (param.leaf) {
            buttons.addToolbar = ""; // 取消新增功能
          }
          return buttons;
        },
        addTreeNode: function (treeNode) {
          $.ajax({
            type: "post",
            data: {parent_id: treeNode.parentId, group_name: treeNode.addNodeName},
            url: STORE_URL + 'system/uplibrary/add_group',
            success: function (result) {
              if (result.code == 200) {
                layer.msg(result.msg, {time: 1000, icon: 1}, function () {
                  DTree.menubarMethod().refreshTree();
                });
              } else {
                layer.msg(result.msg, {time: 1000, icon: 2})
              }
            }
          });
        },
        editTreeNode: function (treeNode, $div) {
          $.ajax({
            type: "post",
            data: {group_id: treeNode.nodeId, group_name: treeNode.editNodeName},
            url: STORE_URL + 'system/uplibrary/edit_group',
            success: function (result) {
              if (result.code == 200) {
                layer.msg(result.msg, {time: 1000, icon: 1}, function () {
                  DTree.menubarMethod().refreshTree();
                });
              } else {
                layer.msg(result.msg, {time: 1000, icon: 2})
              }
            }
          });
        },
        delTreeNode: function (treeNode) {
          $.ajax({
            type: "post",
            data: {group_id: treeNode.nodeId},
            url: STORE_URL + 'system/uplibrary/delete_group',
            success: function (result) {
              if (result.code == 200) {
                layer.msg(result.msg, {time: 1000, icon: 1}, function () {
                  DTree.menubarMethod().refreshTree();
                });
              } else {
                layer.msg(result.msg, {time: 1000, icon: 2})
              }
            }
          });
        }
      }
    });


    /**
     * 移动附件到分组
     */
    function moveFilesToGroup() {
      dtree.renderSelect({
        elem: "#group-select-Tree",
        url: STORE_URL + 'system/uplibrary/group_list',
        width: '195',
        selectTips: "选择图片移动至",
      });
      dtree.on('node("group-select-Tree")', function (obj) {
        var newGroupId = obj.param.nodeId;
        fileIds = getSelectedFileIds();
        if (fileIds.length < 1) {
          layer.msg("请先选择图片", {offset: 't', anim: 6});
          return false;
        }
        layer.confirm('确定移动选中的文件吗？', {title: '友情提示'}, function (index) {
          var loading = layer.load(2);
          $.post(STORE_URL + 'system/uplibrary/move_files', {
            group_id: newGroupId
            , fileIds: fileIds
          }, function (result) {
            layer.close(loading);
            layer.msg(result.msg);
            if (result.code == 200) {
              renderFileList();
            }
          });
          layer.close(index);
        });

      });
    }

    /**
     * 渲染文件列表
     * @param page
     * @param groupId
     */
    function renderFileList(page, groupId = -1) {
      var pageLimit = 18;
      console.log(groupId);
      getJsonData(STORE_URL + 'system/uplibrary/file_list', {
        group_id: groupId,
        page: page,
        pageSize: pageLimit
      }, function (res) {
        resStr = returnResList(res);
        $('#file-list-body').html(resStr);
        laypage.render({
          elem: 'file-list-page'
          , count: res.total
          , limit: pageLimit
          , jump: function (obj) {
            getJsonData(STORE_URL + 'system/uplibrary/file_list', {
              group_id: groupId,
              page: obj.curr,
              pageSize: pageLimit
            }, function (res2) {
              resStr = returnResList(res2);
              $('#file-list-body').html(resStr);
            });
          }
        });
      });
    }

    /**
     * 注册文件选中事件
     */
    function selectFilesEvent(inputType) {
      // 绑定文件选中事件
      var checkNum = 0;
      $('#file-list-body').on('click', '.file-list-item li', function (res) {
        $(this).toggleClass('active');
        let hasActive = $(this).hasClass('active');
        if (hasActive === true) {
          checkNum += 1;
        } else {
          checkNum -= 1;
        }
        if (inputType == 'one' && checkNum > 1) {
          $(this).addClass("active").siblings().removeClass("active");
        }
      });
    }

    /**
     * 请求列表返回数据的html
     */
    function returnResList(res) {
      let str = "";
      let s_height = $(window).height();
      var content_height = Number(s_height) - 180;
      str += '<ul class="file-list-item" style="max-width:960px;max-height:' + content_height + 'px">';
      $.each(res.file_list, function (i, val) {
        str += '<li class="ng-scope" title="' + val.file_name + '" data-file-id="' + val.id + '" data-file-path="' + val.file_url + '">\n' +
          '    <div class="img-cover" style="background-image: url(' + val.file_url + ')">\n' +
          '    </div>\n' +
          '    <p class="file-name am-text-center am-text-truncate">' + val.file_name + '</p>\n' +
          '    <div class="select-mask">\n' +
          '        <img src="/static/admin/images/chose.png">\n' +
          '    </div>\n' +
          '</li>';
      })
      str += '</ul>';
      return str;
    }

    /**
     * 获取文件库列表数据
     * @param params
     * @param success
     */
    function getJsonData(url, params, success) {
      var loadIndex = layer.load();
      typeof params === 'function' && (success = params);
      // 获取文件库列表
      $.post(url, params, function (result) {
        layer.close(loadIndex);
        if (result.code === 200) {
          typeof success === 'function' && success(result.data);
        } else {
          layer.msg(result.msg, {anim: 6});
        }
      });
    }

    /**
     * 文件上传 (多文件)
     */
    function uploadImagesEvent() {
      layui.define('upload', function (exports) {
        let upload = layui.upload;
        var loading = '';
        console.log($('.j-upload').attr('data-group-id'))

        upload.render({
          elem: ".j-upload"
          , url: uploadUrl
          , size: chunkSize
          , accept: 'file'
          , exts: Exts
          , force: 'json'
          , choose: function (obj) {
            loading = layer.load(2);
          }
          , data: {
            group_id: function () {
              return $('.j-upload').attr('data-group-id');
            }
          }
          , done: function (res, index, upload) {
            layer.close(loading);
            if (res.code === 200) {
              var $list = $('ul.file-list-item');
              renderFileList(page, $('.j-upload').attr('data-group-id'));
            } else {
              layer.msg(res.msg, {icon: 2})
            }
          }, error: function (index, upload) {
            console.log(index);
          }
        });
      });
    }

    /**
     * 删除选中的文件
     */
    function deleteFilesEvent() {
      $('.file-delete').on('click', function () {
        var fileIds = getSelectedFileIds();
        if (fileIds.length === 0) {
          layer.msg('您还没有选择任何文件~');
          return;
        }
        layer.confirm('确定删除选中的文件吗？', {title: '友情提示'}, function (index) {
          var load = layer.load();
          $.post(STORE_URL + 'system/uplibrary/delete_files', {
            fileIds: fileIds
          }, function (result) {
            layer.close(load);
            if (result.code === 200) {
              renderFileList();
            }
          });
          layer.close(index);
        });
      });
    }

    /**
     * 获取选中的文件列表
     * @returns {Array}
     */
    function getSelectedFiles() {
      let selectedList = [];
      $('.file-list-item > li.active').each(function (index) {
        let $this = $(this);
        selectedList[index] = {
          file_id: $this.data('file-id')
          , file_path: $this.data('file-path')
        };
      });
      return selectedList;
    }

    /**
     * 获取选中的文件的ID集
     * @returns {Array}
     */
    function getSelectedFileIds() {
      let fileList = getSelectedFiles();
      let data = [];
      fileList.forEach(function (item) {
        data.push(item.file_id);
      });
      return data;
    }

    /**
     * 分类切换事件
     */
    function switchClassEvent() {
      // 绑定节点点击事件
      dtree.on("node(organizationTree)", function (obj) {
        var nodeId = obj.param.nodeId || 0;
        $('.j-upload').attr('data-group-id', nodeId);
        group_id = nodeId;
        renderFileList(1, nodeId);
      });
    }

    /**
     * 确认回调
     */
    function btnDone(inputType, inputSelectId) {
      $('.file-library').on('click', '.btn-sure', function () {
        var selectedList = getSelectedFiles();
        var input_type = inputType;
        var input_select_id = inputSelectId;
        var index = parent.layer.getFrameIndex(window.name);
        if (input_type == 'one') {
          if (selectedList.length > 0) {
            send_result_pic(selectedList[0]['file_path'], input_type, input_select_id)
          }
        } else {
          send_result_pic(selectedList, input_type, input_select_id)
        }
      });
    }

    function FileLibrary(trigger, options, laypage) {
      inputType = options.input_type;
      inputSelectId = options.select_id;
      //获取文件列表
      renderFileList(page, group_id);
      //注册文件选中事件
      selectFilesEvent(inputType);
      //分类切换
      switchClassEvent();
      //上传
      uploadImagesEvent();
      //删除事件
      deleteFilesEvent();
      //移动附件分组
      moveFilesToGroup();
      //回调数据
      btnDone(inputType, inputSelectId);
    }

    $.fn.fileLibrary = function (options) {
      new FileLibrary(this, options);
    };


  });
})));

layui.define(function (exports) {
  exports('fileLibrary', window.fileLibrary);
});
